<template>
	<view class="login-content">
		<view class="top">
			<view class="title" style="font-weight: 700;">
				欢迎来到
			</view>
			<view class="title" style="font-weight: 700;">
				小橙云服售后系统
			</view>
		</view>
		<view class="center" style="margin-bottom: 40px;">
			<view class="u-flex mb-10 change-type">
				<view class="login-type">
					<view class="text-gray mb-5 f700" @click="LoginType = 1" :class="{'active-color': LoginType == 1}">
						密码登录
					</view>
					<view :class="{'active-line': LoginType == 1}">

					</view>
				</view>
				<view class="login-type">
					<view class="text-gray mb-5 f700" @click="LoginType = 2" :class="{'active-color': LoginType == 2}">
						验证码登录
					</view>
					<view :class="{'active-line': LoginType == 2}">

					</view>
				</view>
			</view>
			<u--form labelPosition="left" ref="uForm" :model="LoginForm">
				<view class="">
					<view class="f700">
						手机号
					</view>
					<u-form-item rightIcon="phone">
						<view class="" style="width: 100%;">
							<u--input border="surround" placeholder="请输入手机号" v-model.trim="LoginForm.username" prefixIcon="phone"
								shape="square" prefixIconStyle="font-size: 26px;color: #fd7400" :customStyle="inpBg"
								maxlength="11"></u--input>
						</view>
					</u-form-item>
				</view>
				<view v-show="LoginType == 1">
					<view class="f700">
						密码
					</view>
					<u-form-item>
						<view class="" style="width: 100%;">
							<u--input border="surround" placeholder="请输入密码" v-model.trim="LoginForm.password" prefixIcon="lock"
								:customStyle="inpBg" prefixIconStyle="font-size: 26px;color: #fd7400" type="password"
								shape="square"></u--input>
						</view>
					</u-form-item>
				</view>
				
				<view v-show="LoginType == 2">
					<view class="f700">
						验证码
					</view>
					<u-form-item>
						<view class="u-flex-center pos-r" style="width: 100%;">
							<u--input border="surround" placeholder="请输入验证码" prefixIcon="lock"
								prefixIconStyle="font-size: 26px;color: #fd7400;" v-model.trim="LoginForm.code" shape="square"
								:customStyle="inpBg" maxlength="6">
							</u--input>
							<view class="text-orange pos-a code-btn" v-if="!code_status" @click.native="getCode2">
								{{getCodeText}}
							</view>
							<view class="text-orange pos-a code-btn" v-else>
								{{countdown}} 秒重新获取
							</view>
						</view>
						<view>

						</view>
					</u-form-item>
				</view>
			</u--form>
			<view class="u-flex text-gray fsize14">
				<view class="">
					<u-checkbox-group>
						<u-checkbox shape="square" size="16px" iconSize="16px" activeColor="#fd7400" v-model="agreement_check"
							@change="groupChange" :checked="agreement_check">
						</u-checkbox>
						<view class="u-flex">
							<span @click="agreement_check = !agreement_check">我已阅读</span><p class="text-orange" @click="changePopShowWho('protocol')">用户手册</p>和<p class="text-orange"
								@click="changePopShowWho('privacy')">政策隐私</p>
						</view>
					</u-checkbox-group>
				</view>

			</view>
		</view>
		<view class="login-btn">
			<u-button type="primary" @click="goLogin" shape="square" :customStyle="orangeBtn">登录</u-button>
		</view>
		<view class="dsf">
			<u-divider text="第三方登录" textSize="24"></u-divider>
			<view class="u-flex-center">
				<view class="u-flex-center wechat-login" @click="WxChatLogin">
					<u-icon name="weixin-fill" color="rgb(74, 213, 116)" size="50rpx"></u-icon>
				</view>
			</view>
		</view>
		<!-- 用户/隐私弹窗 -->
		<centerpop 
			:popTitle="popTitle"
			ref="pop-center"
			isSlot="true"
			@saveclick="agreePrivacy"
		>
			<template slot="content">
				<text style="color: gray;">{{popShowWho == 'all' ? popData : (popShowWho == 'protocol' ? protocol : privacy)}}</text>
			</template>
		</centerpop>
	</view>
</template>

<script>
	import {checkStr} from "@/common/js/defaults.js"
	export default {
		data() {
			return {				
				LoginForm: {
					password: '',
					username: '',
					code: ''
				},
				inpBg: {
					background: ' rgba(255, 243, 232, 1)',
					height: '50px',
					border: '0',
					padding: '0px 15px',
				},
				orangeBtn: {
					height: '50px !important',
					background: 'linear-gradient(90deg, rgba(253, 116, 0, 1) 0%, rgba(255, 87, 51, 1) 100%)',
					border: '0',
					boxShadow: '0px 7px 40px  rgba(253, 112, 8, 0.2)',
					borderRadius: '8px',
					fontSize: '18px'
				},
			
				popupStyle: {
					height: '500px',
					width: '360px',
					borderRadius: '10px',
					padding: '10px'
				},
				rulesObj: {
					"phone": {
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					},
					"password": {
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					}
				},
				getCodeText: '获取验证码',
				term_show: false,
				privacy_show: false,
				code_status: false,
				countdown: 60,
			
		
				checkShow: false,
				agreement_check: false,
				
				isLogin: false,
				LoginType: 1,  // 0：非登录  1：密码登录  2：验证码登录  3：第三方登录-微信
				otherLogin: false, //第三方登录 
				
				popShow: false,
				popTitle: '用户协议',	//弹窗标题
				popShowWho: '',			//弹窗内容为：用户协议OR政策协议其中一个
				popData: '',
				protocol: '',			//用户协议
				privacy: ''				//政策协议
			};
		},
		onLoad() {
			uni.clearStorageSync();
			this.getProtocolData();
		},
			
		onBackPress(options) {
		  // 触发返回就会调用此方法，这里实现的是禁用物理返回，顶部导航栏的自定义返回 uni.navigateBack 仍可使用
		  if (options.from == 'backbutton') {
		    return true;
		  } else if (options.from == 'navigateBack') {
		    return false;
		  }
		},
		methods: {
			// 点击 登录
			async goLogin() {
				if(!this.$clickgate(2000)) return
				
				this.isLogin = true;
				
				// 非第三方登录
				this.otherLogin = false;
				if (!this.agreement_check) {
					this.openModel('pop-center');
					this.changePopShowWho('all');
					return
				}
				if(this.LoginType == 1) {
					this.PasswordLogin()
				}
				else if(this.LoginType == 2) {
					this.VcodeLogin()
				}
			},
			// 同意隐私条款
			agreePrivacy() {
				this.agreement_check = true;
				// 第三方登录
				if(this.otherLogin) {
					// 微信登录
					if(this.otherLogin == 'WeChat') {
						this.WxChatLogin()
					};
				}else if(this.isLogin){
					this.isLogin = false;
					if(this.LoginType == 1) {
						// 密码登录
						this.PasswordLogin();
					}else if(this.LoginType == 2) {
						// 验证码登录
						this.VcodeLogin();
					}
				}
				
			},
			// 微信登录
			async WxChatLogin() {
				if (!this.agreement_check) {
					// this.$alertTost('请勾选用户手册和政策隐私')
					this.openModel('pop-center');
					this.changePopShowWho('all');
					this.otherLogin = 'WeChat';
					return
				}
				this.otherLogin = false;
				
				const codeRes = await this.getLoginCode();
				let isLoginRes = await uni.$api.login.userWeChatLogin(codeRes.code);
				console.log('登录状态-----',isLoginRes.code);
				
				const data = encodeURIComponent(JSON.stringify(isLoginRes.data));
				if (isLoginRes.code === 0) {
					let cobj = isLoginRes.data
					// let roleslist = isLoginRes.data.roles
					uni.setStorageSync('data', data)
					uni.setStorageSync('test', this.LoginForm)
					this.setLoginState(cobj)
				} else {
					uni.showModal({
						title: '未绑定微信登录，请先使用密码或验证码进行登录'
					});	
				}
			},
			// 获取登录code
			getLoginCode() {
				return new Promise((resolve, reject) => {
					wx.login({
					  provider: 'weixin', //使用微信登录
					  success: function (res) {
						resolve(res)
					  },
					  fail: function(err) {
						reject(err);
					  }
					});
				})
			},
			
			// 获取协议数据并判断是否需要重新授权
			async getProtocolData() {
				const res = await uni.$api.currency.getProtocolAndPrivacy(); 
				if(res.code == 0) {
					this.isUpdate = res.data.isUpdate;
					this.popData = res.data.protocol + '\n\n\n\n' + res.data.privacy;
					this.protocol = res.data.protocol;
					this.privacy = res.data.privacy;
				}
				console.log('获取协议数据-----',res)
			},
			changePopShowWho(str) {
				this.popShowWho = str;
				if(str == 'protocol') {
					this.popTitle = '用户手册'
				}else if(str == 'privacy'){
					this.popTitle = '政策隐私'
				}else {
					this.popTitle = '用户手册和政策隐私';
				}
				this.openModel('pop-center')
			},
			
			// 密码登录
			async PasswordLogin(){
				let {
					password, username
				} = this.LoginForm
				let phone_flag = checkStr(username, 'phone')
				if(!phone_flag){
					this.$alertTost('请输入正确的手机号')
					return
				}
				if(!password){
					this.$alertTost('请输入密码')
					return
				}
				
				let dataPas = {
					password,
					username,
				}
				let res = await uni.$api.login.userLogin(dataPas)
				this.$alertTost(res.msg)
				const data = encodeURIComponent(JSON.stringify(res.data))
				// console.log('data', data)
				// console.log('res.data', res.data)
				console.log('密码登录状态-----',res.code)
				if (res.code === 0) {
					let cobj = res.data
					// let roleslist = res.data.roles
					uni.setStorageSync('data', data)
					uni.setStorageSync('test', this.LoginForm)
					this.setLoginState(cobj)
				}
			},
			// 验证码登录
			async VcodeLogin(){
				let dataCode = {
					password: this.LoginForm.code,
					username: this.LoginForm.username
				}
				if (!dataCode.username) {
					uni.showModal({
						content: '请输入手机号再获取验证码',
						confirmColor: "#fd7400",
						confirmText: '确认',
					})
				} if (!dataCode.password) {
					uni.showModal({
						content: '请输入验证码',
						confirmColor: "#fd7400",
						confirmText: '确认',
					})
				} else {
					if (dataCode.password.length < 6) {
						uni.showModal({
							content: '请输入6位数验证码',
							confirmColor: "#fd7400",
							confirmText: '确认',
						})
						return
					}
				
					let res = await uni.$api.login.codeLogin(dataCode);
					this.$alertTost(res.msg)
					const data = encodeURIComponent(JSON.stringify(res.data))
					console.log("验证码登录状态----",res.code);
					if (res.code === 0) {
						let cobj = res.data
						uni.setStorageSync('data2', data)
						uni.setStorageSync('test', this.LoginForm)
						uni.navigateTo({
							url: `../login/applytip?data=${cobj}`
						})
					}
				}
			},
			// 2024-5月修改，未完善
			// 5.20日改,暂时开通
			setLoginState(obj){
				console.log(obj)
				let {
					id, name, phone, roles, headimg
				} = obj
				uni.setStorageSync('acId', id)
				// 统一
				uni.setStorageSync('userInfo', JSON.stringify(obj))
				
				uni.navigateTo({
					url: `../login/applytip?data=${JSON.stringify(obj)}`
				})
			},

			groupChange(e) {
				console.log('groupChange', e);
				this.agreement_check = e

			},
			// 该功能即将上线
			ComingSoon() {
				uni.showToast({
					title: '该功能即将上线',
					icon: "none",
				});
			},
			async getCode2() {
				let timer = null
				console.log('倒计时开始')
				if (this.LoginForm.username === '') {
					uni.showModal({
						// title: '提示',
						content: '请先输入手机号',
						confirmColor: "#fd7400",
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					return
				}
				if (this.LoginForm.username.length < 11) {
					uni.showModal({
						content: '请输入正确的手机号',
						confirmColor: "#fd7400",
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					return
				}
				let res = await uni.$api.login.getCode({
					username: this.LoginForm.username,
					type: 'loginCode'
				})
				if (this.isCountingDown) {
					uni.showModal({
						// title: '提示',
						content: '倒计时结束后在发送',
						confirmColor: "#fd7400",
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
				this.code_status = true;
				uni.showModal({
					// title: '提示',
					content: '验证码已发送',
					confirmColor: "#fd7400",
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				timer = setInterval(() => {
					if (this.countdown > 0) {
						this.countdown--;

					} else {
						// 倒计时结束，重置状态
						this.code_status = false;
						this.countdown = 60;
						clearInterval(timer); // 清除定时器
						this.getCodeText = '重新获取'
						// 如果正在倒计时，则不执行获取验证码操作
					}
				}, 1000)

			},
			
			// 新开弹窗
			openModel(ref) {
				if(this.$refs[ref]) {
					this.popShow = true;
					this.$refs[ref].pupshow = true;
				}
			},
			// 关闭弹窗
			closePop() {
				this.popShow = false;
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rulesObj);
		}
	}
</script>

<style lang="scss">
	.w100 {
		width: 100px;
	}

	.u-checkbox-group--row {
		align-items: baseline;
	}

	.u-input:focus {
		border: 1px solid rgba(253, 116, 0, 1) !important;
	}

	.u-input:hover {
		border: 1px solid rgba(253, 116, 0, 1) !important;
	}

	.code-btn {
		right: 20px;
		z-index: 100;
	}

	.mb-75 {
		margin-bottom: 75px;
	}

	.login-type {
		position: relative;

		.active-color {
			color: #000;
			font-weight: 700;
		}

		.active-line {
			content: '';
			height: 3px;
			font-weight: 700;
			font-weight: 700;
			background-color: #fd7400;
			position: relative;
			bottom: 0px;
			transition: width 0.6s;
		}

	}

	.login-content {
		width: 100%;
		min-height: 100vh;
		box-sizing: border-box;

		padding: 30px;
		padding-top: calc(30px + 0px);
		background: linear-gradient(to bottom, rgba(255, 176, 107, 0.2) 0%, rgba(255, 255, 255, 0) 35%, rgba(255, 255, 255, 0) 101%);

		.top {
			margin-top: 60rpx;

			.title {
				font-size: 48rpx;
				line-height: 150%;
			}

			.tip {
				font-size: 28rpx;
				line-height: 150%;
				color: #a6a6a6;
			}
		}

		.center {
			margin-top: 60rpx;

			.u-form {
				margin-bottom: 10px;
			}

			.change-type {
				margin-bottom: 80rpx;
			}

			.login-type {
				margin-right: 20px;
				font-size: 20px;
			}



			/deep/.u-button__text {
				font-size: 28rpx !important;
			}

			.getcode {
				display: flex;
				font-size: 28rpx;
				padding: 10rpx 0;
				margin-bottom: 40rpx;
				margin-top: 12rpx;
				justify-content: flex-end;

				.right {
					color: #fd7400
				}
			}


		}

		.dsf {
			margin-top: 80rpx;
		}

		.wechat-login {
			width: 68px;
			height: 68px;
			background: #f1f1f1c7;
			box-shadow: 0 20px 60px rgba(55, 62, 125, .05);
			border-radius: 50%;
		}
	}
</style>